<template>
  <div>
    <!-- 顶部栏 -->
    <van-nav-bar title="搜索" left-arrow @click-left="$router.go(-1)" />
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 推荐词 -->
    <van-cell-group>
      <van-cell
        v-for="item in gaoliang"
        :key="item"
        :title="item"
        icon="search"
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录" />
      <van-cell title="单元格">
        <template #right-icon>
          <van-icon name="close" class="search-icon" />
        </template>
      </van-cell>
      <van-cell title="单元格">
        <template #right-icon>
          <van-icon name="close" class="search-icon" />
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 历史记录 -->
  </div>
</template>

<script>
import { getKeywords } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '', //搜索推荐关键词
      keywords: []
    }
  },
  methods: {
    onSearch () {
      console.log(this.value)
    },

    async onInput () {
      //判断是否为空
      if (this.value == '') {
        this.keywords = []
        return
      }
      //获取数据  调用方法 发起请求
      let res = await getKeywords({ q: this.value })
      console.log(res)
      this.keywords = res.data.data.options
    }
  },
  //计算属性
  computed: {
    gaoliang () {
      //创建正则:全局匹配当前搜索框内容, g:全局匹配  i:不区分大小写
      let res = new RegExp(this.value, 'gi')
      //map隐射数组
      return this.keywords.map(value =>
        value.replace(
          res,
          match => `<span style="color:#ABA3D8">${match}</span>`
        )
      )
    }
  }
}
</script>

<style></style>
